package com.icss.ah.shop.action;

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.icss.ah.base.action.BaseAction;
import com.icss.ah.base.bean.Json;
import com.icss.ah.base.bean.SyncSelectTree;
import com.icss.ah.base.util.DateUtils;
import com.icss.ah.login.bean.UserInfoBean;
import com.icss.ah.shop.bean.HomeApplicationBean;
import com.icss.j2ee.util.UUID;

/**
 * 店铺维护Action
 * @author sw
 * @date 2016-09-28
 */
@Controller
@Scope("prototype")
public class ShopManageAction extends BaseAction {
	
	private final Logger errlog = Logger.getLogger("E");
	private final Logger infolog = Logger.getLogger("I");
	
	private Json jsonText=new Json();
	
	private static final long serialVersionUID = 1L;
	private HomeApplicationBean homeApplicationBean=new HomeApplicationBean();
	private String shopId;
	private String shopName;
	private String shopAddr;
	private String shopTel;
	private String idcardF;
	private String idcardB;
	private String shopLogo;
	private String shopPic;
	private String shopDesc;
	private String shopArea;
	private String payOnline;
	private String legalPerson;
	private String businessLicense;
	private String businessScope;
	private String bankCode;
	private String ProvinceCode;
	private String cityCode;
	private String bankAccountName;
	private String bankAccount;
	private String level;
	private String shopProvince;
	private String shopCity;
	private String shopCounty;
	private String startMoney;
	
	/**
	 * 店铺页面展示
	 * @return
	 */
	public String toShopInfo(){
		String returnPage = "toShopInfo";
		request = this.getRequest();
		String userCode = (String) request.getSession().getAttribute("userCode");
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("userCode", userCode);
		map.put("corpId", getBaseCorpId());
		//获取是否开店信息
		HashMap accountShop = shopManageService.queryAccountMap(map);
		String applyStatus = accountShop.get("APPLY_STATUS").toString();
		HashMap shopMap = new HashMap();
		String approveStatus = "";
		String areaName = "";
		String areaCode = "";
		//存在店铺申请信息，则查询店铺详细信息及经营区域信息
		if("1".equals(applyStatus)){
			map.put("shopId", accountShop.get("SHOP_ID").toString());
			shopMap = shopManageService.queryShopMap(map);
			approveStatus = shopMap.get("REGISTER_STATUS") == null ? "" : shopMap.get("REGISTER_STATUS").toString();
			List<Map> areaCodes = shopManageService.queryCheckList(map);
			if(areaCodes.size() > 0){
				for (Map aMap : areaCodes) {
					areaCode += aMap.get("AREA_CODE").toString() + ",";
					areaName += aMap.get("ANAME").toString() + ",";
				}
				if(!"".equals(areaCode)){
					areaCode = areaCode.substring(0,areaCode.length() - 1);
					areaName = areaName.substring(0,areaName.length() - 1);
				}
			}
		}
		List bankList = shopService.queryBankList();
		HashMap hm = new HashMap();
		hm.put("level", "2");
		List provinceList = shopService.queryProvinceCityList(hm);
		hm.put("areaPcode", shopMap.get("SHOP_PROVINCE"));
		hm.put("level", "3");
		List cityList = shopService.queryProvinceCityList1(hm);
		hm.put("areaPcode", shopMap.get("SHOP_CITY"));
		hm.put("level", "4");
		List countyList = shopService.queryProvinceCityList1(hm);
		request.setAttribute("areaCode", areaCode);
		request.setAttribute("areaName", areaName);
		request.setAttribute("shopMap", shopMap);
		request.setAttribute("bankList", bankList);
		request.setAttribute("provinceList", provinceList);
		request.setAttribute("cityList", cityList);
		request.setAttribute("countyList", countyList);
		request.setAttribute("approveStatus", approveStatus);
		
		return returnPage;
	}
	
	/**
	 * 保存店铺信息
	 * @return
	 */
	public String saveShop(){
		request = this.getRequest();
		jsonText = new Json();
		try {
			String corpId = getBaseCorpId();
			shopId = (shopId == null || "".equals(shopId)) ? "" : shopId;
			String userCode = (String) request.getSession().getAttribute("userCode");
			
			HashMap<String,Object> map = new HashMap<String,Object>();
			map.put("corpId", corpId);
			map.put("shopName", shopName);
			map.put("shopAddr", shopAddr);
			map.put("shopTel", shopTel);
			map.put("idcardF", idcardF);
			map.put("idcardB", idcardB);
			map.put("shopLogo", shopLogo);
			map.put("shopPic", shopPic);
			map.put("shopDesc", shopDesc);
			map.put("payOnline", payOnline);
			map.put("registerStatus", 0);
			map.put("legalPerson", legalPerson);
			map.put("businessLicense", businessLicense);
			map.put("businessScope", businessScope);
			map.put("bankCode", bankCode);
			map.put("ProvinceCode", ProvinceCode);
			map.put("cityCode", cityCode);
			map.put("bankAccountName", bankAccountName);
			map.put("bankAccount", bankAccount);
			map.put("shopProvince", shopProvince);
			map.put("shopCity", shopCity);
			map.put("shopCounty", shopCounty);
			
			startMoney = startMoney == null||startMoney.equals("") ? "0":startMoney;
			DecimalFormat format = new DecimalFormat("0.00");
			startMoney = format.format(Double.valueOf(startMoney));
			
			map.put("startMoney", startMoney);
			
			//保存店铺信息
			if("".equals(shopId)){
				map.put("shopId", new UUID().toString());
				shopManageService.insertShop(map);
			}else {
				map.put("shopId", shopId);
				shopManageService.updateShop(map);
			}
			//保存店铺经营区域信息
			if(!"".equals(shopArea)){//经营区域不为空，则添加经营区域信息
				shopManageService.deleteShopArea(map);
				String areas[] = shopArea.split(",");
				for (String area : areas) {
					map.put("areaCode", area);
					map.put("shopAreaUuid", new UUID().toString());
					shopManageService.insertShopArea(map);
				}
			}
			
			//更新店铺登录信息表店铺申请信息
			map.put("applyStatus", 1);
			map.put("userCode", userCode);
			shopManageService.updateAccountShop(map);
			
			jsonText.setSuccess(true);
			jsonText.setMsg("保存成功！");
		} catch (Exception e) {
			jsonText.setMsg("保存失败！");
			jsonText.setSuccess(false);
			errlog.error("Login|异常：",e);
		}
		return "jsonText";
	}
	
	/**
	 * 判断店铺名称是否可用
	 */
	public void checkShopNameExist(){
		jsonText = new Json();
		try {
			boolean result = shopManageService.checkShopNameExist(shopName);
			jsonText.setSuccess(result);
		} catch (Exception e) {
			e.printStackTrace();
			jsonText.setSuccess(false);
			jsonText.setMsg(e.getMessage());
			errlog.error("Login|异常：",e);
		}
		str2Resp(JSONObject.fromObject(jsonText).toString());
	}
	
	/**
	 * 获取经营区域数据
	 */
	public void getTree(){
		request = getRequest();
		//id 异步加载展开树时传到后台的id
		//tarEnt 入口编码，以编码为入口编码的节点作为根节点
		//ifAll 是否一次性展示所有数据，1是 0否
		String id = request.getParameter("id");
		id = id == null ? "" : id;
		String ifAll = request.getParameter("ifAll");
		ifAll = ifAll == null ? "1" : ifAll;
		SyncSelectTree selectTree = new SyncSelectTree();
		selectTree.setId(id);
		selectTree.setIfAll(ifAll);
		List<SyncSelectTree> list = shopManageService.getTree(selectTree);
		HashMap map = new HashMap();
		map.put("corpId", getBaseCorpId());
		map.put("shopId", shopId);
		List<Map> checkList = shopManageService.queryCheckList(map);
		checkList = checkList == null ? new ArrayList() : checkList;
		for (SyncSelectTree sst : list) {
			sst.setOpen(true);
			if(sst.getIsParent() && "0".equals(sst.getpId())){
				sst.setNocheck(true);
			}
			String sstAreaCode = sst.getId();
			if(!checkList.isEmpty()){
				for (Map m : checkList) {
					String mAreaCode = m.get("AREA_CODE") == null ? "" : m.get("AREA_CODE").toString();
					if(sstAreaCode.equals(mAreaCode)){
						sst.setChecked(true);
					}
				}
			}
		}
		str2Resp(JSONArray.fromObject(list).toString());
	}
	
	/**
	 * 去申请首页展示页面
	 * @return
	 */
	public String toApplyHomeDisplayPage(){
		String userCode=getUserCodeFromSession();								//当前登录人员账号
		UserInfoBean userInfo=getUserInfo(userCode);							//登录人员信息
		String shopId=userInfo.getShopId();										//绑定店铺id
		String corpId = userInfo.getCorpId();	//公众号id
		
		Map<String, String> map=new HashMap<String, String>();
		map.put("corpId", corpId);
		map.put("shopId", shopId);
		
		homeApplicationBean=shopManageService.getHomeApplicationInfo(map);
		
		if(homeApplicationBean!=null){
			homeApplicationBean.setBEG_TIME_STRING(timestampToString(homeApplicationBean.getBEG_TIME()));
			homeApplicationBean.setEND_TIME_STRING(timestampToString(homeApplicationBean.getEND_TIME()));
			getRequest().getSession().setAttribute("homeApplicationBean", homeApplicationBean);
		}else{
			getRequest().getSession().removeAttribute("homeApplicationBean");
			
		}
		
		return "toApplyHomeDisplayPage";
	}
	
	/**
	 * 保存申请首页展示
	 */
	public String applyHomeDisplay(){
		String userCode=getUserCodeFromSession();								//当前登录人员账号
		UserInfoBean userInfo=getUserInfo(userCode);							//登录人员信息
		String shopId=userInfo.getShopId();										//绑定店铺id
		String corpId = userInfo.getCorpId();	//公众号id
		
		homeApplicationBean.setAPPLICATION_UUID(new UUID().toString());
		homeApplicationBean.setCORP_ID(corpId);
		homeApplicationBean.setSHOP_ID(shopId);
		homeApplicationBean.setBEG_TIME(Timestamp.valueOf(homeApplicationBean.getBEG_TIME_STRING()));
		homeApplicationBean.setEND_TIME(Timestamp.valueOf(homeApplicationBean.getEND_TIME_STRING()));
		homeApplicationBean.setAPPLICATION_TIME(Timestamp.valueOf(DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss")));
		homeApplicationBean.setAPPLICATION_STATUS("0");
		homeApplicationBean.setCREATE_TIME(Timestamp.valueOf(DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss")));
		homeApplicationBean.setUPDATE_TIME(Timestamp.valueOf(DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss")));
		
		boolean result=shopManageService.applyHomeDisplay(homeApplicationBean);
		
		if(result){
			jsonText.setSuccess(true);
		}else{
			jsonText.setSuccess(false);
		}
		return "jsonText";
	}
	
	/**
	 * Timestamp转化为string
	 * @param time
	 * @return
	 */
	private  String timestampToString(Timestamp time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINESE);
		String str = "";
		if (time != null){
			str = sdf.format(time);
		}
		return str;
	}
	
	/**
	 * 修改宣传信息
	 * @return
	 */
	public String upDateApplyHomeDisplay(){
		
		homeApplicationBean.setBEG_TIME(Timestamp.valueOf(homeApplicationBean.getBEG_TIME_STRING()));
		homeApplicationBean.setEND_TIME(Timestamp.valueOf(homeApplicationBean.getEND_TIME_STRING()));
		homeApplicationBean.setUPDATE_TIME(Timestamp.valueOf(DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss")));
		
		boolean result=shopManageService.upDateApplyHomeDisplay(homeApplicationBean);
		
		if(result){
			jsonText.setSuccess(true);
		}else{
			jsonText.setSuccess(false);
		}
		return "jsonText";
	}
	
	/**
	 * 再次申请提交信息
	 * @return
	 */
	public String applyAgain(){
		homeApplicationBean.setBEG_TIME(Timestamp.valueOf(homeApplicationBean.getBEG_TIME_STRING()));
		homeApplicationBean.setEND_TIME(Timestamp.valueOf(homeApplicationBean.getEND_TIME_STRING()));
		homeApplicationBean.setUPDATE_TIME(Timestamp.valueOf(DateUtils.getCurrentDate("yyyy-MM-dd HH:mm:ss")));
		homeApplicationBean.setAPPLICATION_STATUS("0");//审核状态改为待审核
		
		boolean result=shopManageService.applyAgain(homeApplicationBean);
		
		if(result){
			jsonText.setSuccess(true);
		}else{
			jsonText.setSuccess(false);
		}
		return "jsonText";
		
		
	}

	public String getShopId() {
		return shopId;
	}

	public void setShopId(String shopId) {
		this.shopId = shopId;
	}

	public String getShopName() {
		return shopName;
	}

	public void setShopName(String shopName) {
		this.shopName = shopName;
	}

	public String getShopAddr() {
		return shopAddr;
	}

	public void setShopAddr(String shopAddr) {
		this.shopAddr = shopAddr;
	}

	public String getShopTel() {
		return shopTel;
	}

	public void setShopTel(String shopTel) {
		this.shopTel = shopTel;
	}

	public String getIdcardF() {
		return idcardF;
	}

	public void setIdcardF(String idcardF) {
		this.idcardF = idcardF;
	}

	public String getIdcardB() {
		return idcardB;
	}

	public void setIdcardB(String idcardB) {
		this.idcardB = idcardB;
	}

	public String getShopPic() {
		return shopPic;
	}

	public void setShopPic(String shopPic) {
		this.shopPic = shopPic;
	}

	public String getShopDesc() {
		return shopDesc;
	}

	public void setShopDesc(String shopDesc) {
		this.shopDesc = shopDesc;
	}

	public Json getJsonText() {
		return jsonText;
	}

	public void setJsonText(Json jsonText) {
		this.jsonText = jsonText;
	}

	public String getShopArea() {
		return shopArea;
	}

	public void setShopArea(String shopArea) {
		this.shopArea = shopArea;
	}

	public HomeApplicationBean getHomeApplicationBean() {
		return homeApplicationBean;
	}

	public void setHomeApplicationBean(HomeApplicationBean homeApplicationBean) {
		this.homeApplicationBean = homeApplicationBean;
	}

	public String getLegalPerson() {
		return legalPerson;
	}

	public void setLegalPerson(String legalPerson) {
		this.legalPerson = legalPerson;
	}

	public String getBusinessLicense() {
		return businessLicense;
	}

	public void setBusinessLicense(String businessLicense) {
		this.businessLicense = businessLicense;
	}

	public String getBusinessScope() {
		return businessScope;
	}

	public void setBusinessScope(String businessScope) {
		this.businessScope = businessScope;
	}

	public String getBankCode() {
		return bankCode;
	}

	public void setBankCode(String bankCode) {
		this.bankCode = bankCode;
	}

	public String getProvinceCode() {
		return ProvinceCode;
	}

	public void setProvinceCode(String provinceCode) {
		ProvinceCode = provinceCode;
	}

	public String getCityCode() {
		return cityCode;
	}

	public void setCityCode(String cityCode) {
		this.cityCode = cityCode;
	}

	public String getBankAccountName() {
		return bankAccountName;
	}

	public void setBankAccountName(String bankAccountName) {
		this.bankAccountName = bankAccountName;
	}

	public String getBankAccount() {
		return bankAccount;
	}

	public void setBankAccount(String bankAccount) {
		this.bankAccount = bankAccount;
	}

	public String getShopLogo() {
		return shopLogo;
	}

	public void setShopLogo(String shopLogo) {
		this.shopLogo = shopLogo;
	}

	public String getPayOnline() {
		return payOnline;
	}

	public void setPayOnline(String payOnline) {
		this.payOnline = payOnline;
	}

	public String getLevel() {
		return level;
	}

	public void setLevel(String level) {
		this.level = level;
	}

	public String getShopProvince() {
		return shopProvince;
	}

	public void setShopProvince(String shopProvince) {
		this.shopProvince = shopProvince;
	}

	public String getShopCity() {
		return shopCity;
	}

	public void setShopCity(String shopCity) {
		this.shopCity = shopCity;
	}

	public String getShopCounty() {
		return shopCounty;
	}

	public void setShopCounty(String shopCounty) {
		this.shopCounty = shopCounty;
	}

	public String getStartMoney() {
		return startMoney;
	}

	public void setStartMoney(String startMoney) {
		this.startMoney = startMoney;
	}
	
}
